//index.js
//获取应用实例
import encode from '../../../utils/base64.js';
import request from '../../../utils/config.js';
let WXBizDataCrypt = require('../../../utils/RdWXBizDataCrypt.js');
const app = getApp();

Page({
  data: {
    ossImgUrL: 'https://winhc.oss-cn-shanghai.aliyuncs.com/xcx/',
    secret: 'f7d98be3828da3b7ab5a2402b9ffcd8e',
    access_token: '',
    showCardInfo: true,
    showlocation: "none",
    fieldArea: "未填写",
    viewAvatarUrlList: new Array,
    imagesList: new Array(),
    personageData: {},
    showImage: 'none',
    hideImage: 'none',
    defaultImg: "",
    defaultName: "",
    opengidName: '',
    showInput: false,
    showModel:false
  },


  onUnload: function (options) {
   
  },

  //下拉刷新
  onPullDownRefresh: function () {
    if (!app.globalData.userInfo) {
      this.setData({
        showModel: true
      })
    } else {
      this.getLoginInfo(this);
      setTimeout(function () {
        wx.showToast({
          title: '加载成功',
          icon: 'success',
          duration: 1000
        })
        wx.stopPullDownRefresh();
      }, 1000);

    }
    console.log("执行了一次下拉刷新")
  },

  onShow: function () {
    this.setData({
      defaultImg: app.globalData.userInfo.avatarUrl,
      defaultName: app.globalData.userInfo.nickName,
      personageData: app.globalData.persionalInfo
    })
    wx.showShareMenu({
      withShareTicket: true
    })
    if (!app.globalData.userInfo) {
      // 获取用户信息
      let _that = this;
      app.getAuthUserInfo((res)=>{
          // 可以将 res 发送给后台解码出 unionId
          res.userInfo.nickName = res.userInfo.nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
          app.globalData.userInfo = res.userInfo;
          wx.showLoading({
            title: '加载中',
          })
          _that.getOpenid(_that);
      },(res)=>{
          console.log("获取用户信息失败=", res)
          _that.setData({
            showModel: true
          })
      });
    } else {
      this.getLoginInfo(this);
    }
  },

  //组件授权回调
  _setAuthorization: function (e) {
    let that = this;
    let res = e.detail;
    that.getOpenid(that);
  },

  //事件处理函数
  bindViewTap: function () {
    wx.navigateTo({
      url: '../logs/logs'
    })
  },

  //点击创建名片
  createCard: function () {
    if (!app.globalData.userInfo) {
      this.setData({
        showModel: true
      })
    } else {
      wx.stopPullDownRefresh();
      wx.navigateTo({
        url: '../createCard/createCard?id=1'
      })
    }
  },

  //查看人气
  seeMoods: () => {
    wx.navigateTo({
      url: '../moods/moods',
    })
  },

  //查看点赞
  seeZan: () => {
    wx.navigateTo({
      url: '../zan/zan',
    })
  },

  //查看留言
  seeLiuyan: () => {
    wx.navigateTo({
      url: '../liuyan/liuyan',
    })
  },

  //查看我的人脉
  seeContacts: function () {
    wx.navigateTo({
      url: '../collect/collect',
    })
  },
  toHideImage: function () {
    this.setData({
      showImage: 'none',
      hideImage: 'flex'
    })
  },

  //点击图片预览
  showPic: function () {
    var picUrl = this.data.personageData.avatarUrl;
    wx.previewImage({
      current: picUrl, // 当前显示图片的http链接
      urls: [picUrl] // 需要预览的图片http链接列表
    })
  },

  //编辑卡片
  editCard: function () {
    // this.dialog.showDialog();
    wx.navigateTo({
      url: '../newEditCard/newEditCard'
    })
  },

  // 点击显示意见反馈
  giveUsMeg: function () {
    this.setData({
      showInput: true
    })
  },

  // 确定提交意见反馈
  confirmMsg: function () {

  },

  // 取消提交意见反馈
  cancleMsg: function () {
    this.setData({
      showInput: false
    })
  },

  //获取openid
  getOpenid: (_that) => {
    console.log("app.globalData.code:" + app.globalData.code);
    request.request_api(app.globalData.code, (data) => {
      console.log("openid成功", data)
      app.globalData.openid = data.data.openid;
      app.globalData.session_key = data.data.session_key;
      _that.getLoginInfo(_that);
    }, (data) => {
      wx.hideLoading();
      console.log("openid失败", data)
    });
  },

  //获取登录信息
  getLoginInfo: (_that) => {
    //获取第三方接口登录数据
    let bodyInfo = {
      openid: app.globalData.openid,
      mobileNo: app.globalData.mobileNo,
      unionid: app.globalData.unionid,
      nickName: app.globalData.userInfo.nickName,
      avatarUrl: app.globalData.userInfo.avatarUrl
    };
    request.get_api("login", bodyInfo, (res) => {
      wx.hideLoading();
      console.log("获取信息成功=", res)
      let bodyData = JSON.parse(res.data.body);
      if (res.data.isSuccess == 'T' && bodyData.memUserInfo.mobileNo) {
        //保存数据
        app.globalData.persionalInfo = bodyData.memUserInfo;
        // let mobileNo = app.globalData.persionalInfo.mobileNo;
        // app.globalData.persionalInfo.mobileNo = String(mobileNo).substr(0, 3) + '-' + String(mobileNo).substr(3, 4) + '-' + String(mobileNo).substr(7, 4);
        var showlocationFlag = 'none';
        if (app.globalData.persionalInfo.address) {
          showlocationFlag = 'block';
        }
        let tempImgList = new Array;
        if (app.globalData.persionalInfo.images) {
          tempImgList = JSON.parse(app.globalData.persionalInfo.images);
          if (tempImgList.length > 0) {
            _that.setData({
              showImage: 'block',
              hideImage: 'none'
            })
          }
        }
        let advField = "未填写";
        if (app.globalData.persionalInfo.advField) {
          advField = app.globalData.persionalInfo.advField.replace(/,/g, " | ");
        }
        let tempAvatarList = bodyData.avatarUrlList;
        let viewAvatarUrlList = new Array();
        tempAvatarList.forEach(function(e){
          if(e){
            viewAvatarUrlList.push(e);
          }
        });
        // console.log("viewAvatarUrlList==", viewAvatarUrlList)
        if (viewAvatarUrlList) {
          if (viewAvatarUrlList.length > 5) {
            viewAvatarUrlList = viewAvatarUrlList.splice(0, 5);
          }
        } else {
          viewAvatarUrlList = new Array();
        }
        _that.setData({
          showCardInfo: false,
          personageData: app.globalData.persionalInfo,
          imagesList: tempImgList,
          fieldArea: advField,
          viewAvatarUrlList: viewAvatarUrlList,
          showlocation: showlocationFlag
        });
      } else {
        _that.setData({
          showCardInfo: true
        });
        wx.hideShareMenu();
      }
    }, (res) => {
      wx.hideLoading();
      console.log("获取信息失败=", res)
    });
  },

  // 拨打电话 
  callPhone: function () {
    var _this = this;
    wx.getSystemInfo({
      success: function (res) {
        // console.log('操作系统版本',res.system) //操作系统版本
        if (res.system.indexOf('iOS') != -1) {
          wx.makePhoneCall({
            phoneNumber: _this.data.personageData.mobileNo //仅为示例，并非真实的电话号码
          })
        } else if (res.system.indexOf('Android') != -1) {
          wx.showModal({
            title: '提示',
            content: '确定呼出电话？',
            success: function (res) {
              if (res.confirm) {
                wx.makePhoneCall({
                  phoneNumber: _this.data.personageData.mobileNo //仅为示例，并非真实的电话号码
                })
              } else if (res.cancel) {

              }
            }
          })
        }
      }
    })
  },

  //打开地图
  openMap: function () {
    wx.openLocation({
      latitude: this.data.personageData.latitude * 1,
      longitude: this.data.personageData.longitude * 1,
      address: this.data.personageData.address,
      scale: 18
    })
  },

  //显示图片
  showIndexImage: function (e) {
    //存储需要的数据
    let tempData = {
      avatarUrl: this.data.personageData.avatarUrl,
      userName: this.data.personageData.userName,
      time: this.data.personageData.openTime,
      images: JSON.parse(this.data.personageData.images)
    }
    wx.setStorageSync('showMoreImgList', tempData);
    var indexKey = e.target.dataset.key;
    wx.navigateTo({
      url: '../photoalbum/photoalbum?key=' + indexKey
    })
  },

  //获取小程序码
  getAppletCode: function () {
    this.getAppletQrCode();
  },

  //获取小程序码access_token
  getAppletQrCode: function () {
    let qrUrl = "pages/card/otherIndex/otherIndex?openid=" + app.globalData.openid;
    console.log(qrUrl);
    var base64Code = encode.encode(qrUrl);
    app.globalData.qrData = request.request_url + "miniqrQr?path=" + base64Code + "&width=150";
    let transData = {
      name: app.globalData.persionalInfo.userName ? app.globalData.persionalInfo.userName : app.globalData.persionalInfo.nickName,
      avatarUrl: app.globalData.persionalInfo.avatarUrl
    }
    wx.navigateTo({
      url: '../appletQr/appletQr?transData=' + JSON.stringify(transData)
    })
  },
  goEditCard: function () {
    wx.navigateTo({
      url: '../newEditCard/newEditCard',
    })
  },

  onLoad: function () {
    wx.showShareMenu({
      withShareTicket: true
    })

  },

  /**
 * 生命周期函数--监听页面初次渲染完成
 */
  onReady: function () {
    this.foot = this.selectComponent("#footer");
    this.toast = this.selectComponent("#toast");
  },

  //点击去名片
  _gocardEvent: function () {
    // wx.navigateTo({
    //   url: '',
    // })
  },

  //点击去通讯录 
  _goipaEvent: function () {
    wx.redirectTo({
      url: '../addressBook/addressBook',
    })
  },

  //点击去首页
  _goindEvent: function(){
    wx.redirectTo({
      url: '../../index/index',
    })
  },

  //转发
  onShareAppMessage: function (res) {
    var picUrl = this.data.personageData.avatarUrl
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log("来自页面内的转发", res.target)
    }
    let This = this;
    return {
      title: '您好，这是我的名片，请惠存',
      path: 'pages/card/otherIndex/otherIndex?openid=' + app.globalData.openid,
      // imageUrl: picUrl,
      success: function (res) {
        // 转发成功
        console.log("转发成功返回数据=", res)
        wx.showShareMenu({
          // 要求小程序返回分享目标信息
          withShareTicket: true
        });

        if (res.shareTickets) {
          // 获取转发详细信息
          wx.getShareInfo({
            shareTicket: res.shareTickets[0],
            success(res) {
              // res.errMsg; // 错误信息
              // res.encryptedData;  //  解密后为一个 JSON 结构（openGId    群对当前小程序的唯一 ID）
              // res.iv; // 加密算法的初始向量
              let pc = new WXBizDataCrypt(app.globalData.appid, app.globalData.session_key);
              let decodeData = pc.decryptData(res.encryptedData, res.iv);
              console.log('解密后 decodeData: ', decodeData);
              This.setData({
                opengidName: decodeData.openGId
              });
            },
            fail() { },
            complete() { }
          });
        }
      },
      fail: function (res) {
        // 转发失败
      },
      complete: function () {

      }
    }
  }
})
